package com.ls.controller;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.ls.utils.ResultData;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

//import io.swagger.annotations.Api;

/**
 * Created by pengyu on 2020/6/1.
 * windows Linux 下 相对路径不一样 ，dev 和 pro 不一样
 */

@Api(value = "文件上传接口", tags = "文件上传接口")
@Slf4j
@RestController
public class FileController {

    /**
     * 时间格式化
     */
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");

    /**
     * 图片保存路径，自动从yml文件中获取数据
     * 示例： E:/images/
     */
    @Value("${file-save-path}")
    private String fileSavePath;
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.access-key-id}")
    private String accessKeyId;
    @Value("${aliyun.oss.access-key-secret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucket-name}")
    private String bucketName;
    @Value("${aliyun.oss.url-prefix}")
    private String urlPrefix;
    /** 上传文件 */
    @PostMapping(path = "/upload")
    public ResultData uploadFile(MultipartFile file, HttpServletRequest request) {
        log.info("开始上传文件:{}",file);
        //最大上传5TB
        long maxSize = 5L * 1024 * 1024 * 1024 * 1024;
        if (file.getSize() > maxSize) {
            return ResultData.failure("上传文件不能超过5TB");
        }
        OSS ossClient = null;
        try {
            // 初始化OSS客户端
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            //1.后半段目录：  2020/03/15
            String directory = simpleDateFormat.format(new Date());
            //3.给文件重新设置一个名字
            //后缀
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String fileName = fileSavePath+directory + UUID.randomUUID().toString().replaceAll("-", "") + suffix;
            // 上传文件到OSS
            ossClient.putObject(bucketName, fileName, file.getInputStream());
            // 生成访问URL（直接使用配置的URL前缀）
            String url = urlPrefix + fileName;
            log.info("文件上传至OSS，访问URL：" + url);

            ossClient.shutdown();
            return ResultData.successData(url);
        } catch (Exception e) {
            log.error("OSS连接异常", e);
            return ResultData.failure("文件服务不可用");
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

